﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using ShortLink.Common.Exceptions;
using ShortLink.Common.Results;

namespace ShortLink.Extensions.Exceptions
{
    public class ExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionMiddleware> _logger;

        public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context); // 执行下一个中间件
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "全局异常捕获");
                await HandleExceptionAsync(context, ex);
            }
        }

        private static Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            var data = exception is BizException bizException
                ? JsonData.BuildCodeAndMsg(bizException.Code, bizException.Message)
                : JsonData.BuildCodeAndMsg(500, $"未知错误: {exception.Message}");

            return context.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(data));
        }
    }
}
